package br.com.hd.dao;

import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;

import org.hibernate.Criteria;
import org.hibernate.criterion.Restrictions;

import br.com.hd.entity.Responsavel;
import br.com.hd.entity.ResponsavelDepartamento;
import br.com.hd.util.HibernateUtility;

public class ResponsavelDepartamentoDAO extends DAO {

	private static ResponsavelDepartamentoDAO instance;

	private ResponsavelDepartamentoDAO() {
	}

	public static ResponsavelDepartamentoDAO getInstance() {
		if (instance == null) {
			instance = new ResponsavelDepartamentoDAO();
		}
		return instance;
	}

	public void saveOrUpdate(Object objeto, boolean ultimo) {
		FacesMessage message = null;
		try {
			HibernateUtility.getSession().clear();
			HibernateUtility.beginTransaction();
			HibernateUtility.getSession().saveOrUpdate(objeto);
			HibernateUtility.commitTransaction();
			if (ultimo) {
				message = new FacesMessage(FacesMessage.SEVERITY_INFO,
						"Cadastro realizado com sucesso!",
						"Cadastro realizado sucesso!");
				FacesContext.getCurrentInstance().addMessage("", message);
			}
		} catch (Exception e) {
			HibernateUtility.rollbackTransaction();
			message = new FacesMessage(FacesMessage.SEVERITY_ERROR,
					"Erro ao comunicar com o servidor!",
					"Erro ao comunicar com o servidor!");
			FacesContext.getCurrentInstance().addMessage("", message);
		}
	}
	
	
	@SuppressWarnings("unchecked")
	public List<ResponsavelDepartamento> buscarDepartamentos(Responsavel responsavel) {
		HibernateUtility.getSession().flush();
		HibernateUtility.beginTransaction();
		Criteria c = HibernateUtility.getSession()
				.createCriteria(ResponsavelDepartamento.class);
		c.add(Restrictions.eq("responsavel", responsavel));
		//HibernateUtility.commitTransaction();
		return  c.list();
	}

}